/*
* © 2010 Autodata Solutions Company. All Rights Reserved
* This source code is the confidential and proprietary information of Autodata Solutions Company.
* The user shall not, in whole or in part, copy, publish, disclose or make any use of this source code
* without the prior written consent of Autodata Solutions Company.
*/

Ext.ns('net.autodata.compare.data');
(function() {

    var Proxy = Ext.extend(Ext.data.DataProxy, {

        constructor: function() {
            var api = {};
            api[Ext.data.Api.actions.read] = true;
            Proxy.superclass.constructor.call(this, { api: api });
        },

        doRequest: function(action, rs, params, reader, callback, scope, arg) {
            // No implementation for CRUD in MemoryProxy.  Assumes all actions are 'load'

            //Grab the base vehicle, competitors and common competitors from Session
            var session = net.autodata.Session.getInstance();
            var vehicles = session.vehicles;
            var ccs = new Ext.util.MixedCollection(false);
            ccs.addAll(vehicles.getCommonCompetitors(true));

            var rows = [];

            // if there are common competitors, then cycle through them and ensure 
            // that the competitors in the list are common competitors
            if (ccs.getCount() > 0) {

                vehicles.eachCompetitor(function(competitor) {
                    if (competitor) {
                        var found = false;
                        ccs.each(function(cc) {
                            if (cc && competitor.acode == cc.acode) {
                                found = true;
                                return false;
                            }
                        }, ccs);

                        if (!found) {
                            rows.push({});
                            return true;
                        }
                    }

                    rows.push(competitor ? competitor : {});
                });
            }

            var data = {
                rows: rows
            };

            try {
                result = reader.readRecords(data);
            } catch (e) {
                // @deprecated loadexception
                this.fireEvent("loadexception", this, null, arg, e);

                this.fireEvent('exception', this, 'response', action, arg, null, e);
                callback.call(scope, null, arg, false);
                return;
            }
            callback.call(scope, result, arg, true);
        }
    });

    net.autodata.compare.data.CommonCompetitorVehiclesSessionProxy = Proxy;
})();